package com.dianganjiao.lib.util

import android.graphics.Bitmap
import android.text.TextUtils
import com.dianganjiao.lib.AppContext
import java.io.ByteArrayOutputStream
import java.io.File


/**
 * create file time : 2021/3/15
 * create user : wxl
 * subscribe :
 */

class FileCommon {
    companion object {

        fun getSdCardRootPath(): String {
           AppContext.appContext.getApplication()
                .getExternalFilesDir(android.os.Environment.DIRECTORY_PICTURES)?.let {
                return it.absolutePath
            }
            return ""
        }

        fun getExternalFileRootPath() : String {
            val rootPath = getSdCardRootPath()
            if(!TextUtils.isEmpty(rootPath)){
                val file = File("$rootPath/dswb")
                if(!file.exists()){
                    file.mkdir()
                }
                return file.absolutePath
            }
            return ""
        }

        fun getExternalImageFile(): File?{
            val path = getExternalFileRootPath()
            if(!TextUtils.isEmpty(path)){
                val dir = File("$path/pic")
                if(!dir.exists()){
                    dir.mkdir()
                }
                val file = File("${dir.absolutePath}/${System.currentTimeMillis()}.png")
                file.createNewFile()
                return file
            }
            return null
        }

        fun bmpToByteArray(bmp: Bitmap, needRecycle: Boolean): ByteArray {
            val output = ByteArrayOutputStream()
            bmp.compress(Bitmap.CompressFormat.PNG, 100, output)
            if (needRecycle) {
                bmp.recycle()
            }
            val result: ByteArray = output.toByteArray()
            try {
                output.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return result
        }

        fun buildTransaction(type: String?): String {
            return if (type == null) System.currentTimeMillis()
                .toString() else type + System.currentTimeMillis()
        }
    }
}